home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / tempfile.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  17.1 KB  |  469 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. '''Temporary files.
  5.  
  6. This module provides generic, low- and high-level interfaces for
  7. creating temporary files and directories.  The interfaces listed
  8. as "safe" just below can be used without fear of race conditions.
  9. Those listed as "unsafe" cannot, and are provided for backward
  10. compatibility only.
  11.  
  12. This module also provides some data items to the user:
  13.  
  14.   TMP_MAX  - maximum number of names that will be tried before
  15.              giving up.
  16.   template - the default prefix for all temporary names.
  17.              You may change this to control the default prefix.
  18.   tempdir  - If this is set to a string before the first use of
  19.              any routine from this module, it will be considered as
  20.              another candidate location to store temporary files.
  21. '''
  22. __all__ = [
  23.     'NamedTemporaryFile',
  24.     'TemporaryFile',
  25.     'mkstemp',
  26.     'mkdtemp',
  27.     'mktemp',
  28.     'TMP_MAX',
  29.     'gettempprefix',
  30.     'tempdir',
  31.     'gettempdir']
  32. import os as _os
  33. import errno as _errno
  34. from random import Random as _Random
  35. if _os.name == 'mac':
  36.     import Carbon.Folder as _Folder
  37.     import Carbon.Folders as _Folders
  38.  
  39.  
  40. try:
  41.     import fcntl as _fcntl
  42.     _fcntl.fcntl
  43. except (ImportError, AttributeError):
  44.     
  45.     def _set_cloexec(fd):
  46.         pass
  47.  
  48.  
  49.  
  50. def _set_cloexec(fd):
  51.     flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
  52.     if flags >= 0:
  53.         flags |= _fcntl.FD_CLOEXEC
  54.         _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
  55.     
  56.  
  57.  
  58. try:
  59.     import thread as _thread
  60. except ImportError:
  61.     import dummy_thread as _thread
  62.  
  63. _allocate_lock = _thread.allocate_lock
  64. _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
  65. if hasattr(_os, 'O_NOINHERIT'):
  66.     _text_openflags |= _os.O_NOINHERIT
  67.  
  68. if hasattr(_os, 'O_NOFOLLOW'):
  69.     _text_openflags |= _os.O_NOFOLLOW
  70.  
  71. _bin_openflags = _text_openflags
  72. if hasattr(_os, 'O_BINARY'):
  73.     _bin_openflags |= _os.O_BINARY
  74.  
  75. if hasattr(_os, 'TMP_MAX'):
  76.     TMP_MAX = _os.TMP_MAX
  77. else:
  78.     TMP_MAX = 10000
  79. template = 'tmp'
  80. tempdir = None
  81. _once_lock = _allocate_lock()
  82.  
  83. class _RandomNameSequence:
  84.     '''An instance of _RandomNameSequence generates an endless
  85.     sequence of unpredictable strings which can safely be incorporated
  86.     into file names.  Each string is six characters long.  Multiple
  87.     threads can safely use the same instance at the same time.
  88.  
  89.     _RandomNameSequence is an iterator.'''
  90.     characters = 'abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + '0123456789-_'
  91.     
  92.     def __init__(self):
  93.         self.mutex = _allocate_lock()
  94.         self.rng = _Random()
  95.         self.normcase = _os.path.normcase
  96.  
  97.     
  98.     def __iter__(self):
  99.         return self
  100.  
  101.     
  102.     def next(self):
  103.         m = self.mutex
  104.         c = self.characters
  105.         choose = self.rng.choice
  106.         m.acquire()
  107.         
  108.         try:
  109.             letters = [ choose(c) for dummy in '123456' ]
  110.         finally:
  111.             m.release()
  112.  
  113.         return self.normcase(''.join(letters))
  114.  
  115.  
  116.  
  117. def _candidate_tempdir_list():
  118.     '''Generate a list of candidate temporary directories which
  119.     _get_default_tempdir will try.'''
  120.     dirlist = []
  121.     for envname in ('TMPDIR', 'TEMP', 'TMP'):
  122.         dirname = _os.getenv(envname)
  123.         if dirname:
  124.             dirlist.append(dirname)
  125.             continue
  126.     
  127.     if _os.name == 'mac':
  128.         
  129.         try:
  130.             fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk, _Folders.kTemporaryFolderType, 1)
  131.             dirname = fsr.as_pathname()
  132.             dirlist.append(dirname)
  133.         except _Folder.error:
  134.             pass
  135.         except:
  136.             None<EXCEPTION MATCH>_Folder.error
  137.         
  138.  
  139.     None<EXCEPTION MATCH>_Folder.error
  140.     if _os.name == 'riscos':
  141.         dirname = _os.getenv('Wimp$ScrapDir')
  142.         if dirname:
  143.             dirlist.append(dirname)
  144.         
  145.     elif _os.name == 'nt':
  146.         dirlist.extend([
  147.             'c:\\temp',
  148.             'c:\\tmp',
  149.             '\\temp',
  150.             '\\tmp'])
  151.     else:
  152.         dirlist.extend([
  153.             '/tmp',
  154.             '/var/tmp',
  155.             '/usr/tmp'])
  156.     
  157.     try:
  158.         dirlist.append(_os.getcwd())
  159.     except (AttributeError, _os.error):
  160.         dirlist.append(_os.curdir)
  161.  
  162.     return dirlist
  163.  
  164.  
  165. def _get_default_tempdir():
  166.     '''Calculate the default directory to use for temporary files.
  167.     This routine should be called exactly once.
  168.  
  169.     We determine whether or not a candidate temp dir is usable by
  170.     trying to create and write to a file in that directory.  If this
  171.     is successful, the test file is deleted.  To prevent denial of
  172.     service, the name of the test file must be randomized.'''
  173.     namer = _RandomNameSequence()
  174.     dirlist = _candidate_tempdir_list()
  175.     flags = _text_openflags
  176.     for dir in dirlist:
  177.         if dir != _os.curdir:
  178.             dir = _os.path.normcase(_os.path.abspath(dir))
  179.         
  180.         for seq in xrange(100):
  181.             name = namer.next()
  182.             filename = _os.path.join(dir, name)
  183.             
  184.             try:
  185.                 fd = _os.open(filename, flags, 384)
  186.                 fp = _os.fdopen(fd, 'w')
  187.                 fp.write('blat')
  188.                 fp.close()
  189.                 _os.unlink(filename)
  190.                 del fp
  191.                 del fd
  192.                 return dir
  193.             continue
  194.             except (OSError, IOError):
  195.                 e = None
  196.                 if e[0] != _errno.EEXIST:
  197.                     break
  198.                 
  199.                 e[0] != _errno.EEXIST
  200.             
  201.  
  202.         
  203.     
  204.     raise IOError, (_errno.ENOENT, 'No usable temporary directory found in %s' % dirlist)
  205.  
  206. _name_sequence = None
  207.  
  208. def _get_candidate_names():
  209.     '''Common setup sequence for all user-callable interfaces.'''
  210.     global _name_sequence
  211.     if _name_sequence is None:
  212.         _once_lock.acquire()
  213.         
  214.         try:
  215.             if _name_sequence is None:
  216.                 _name_sequence = _RandomNameSequence()
  217.         finally:
  218.             _once_lock.release()
  219.  
  220.     
  221.     return _name_sequence
  222.  
  223.  
  224. def _mkstemp_inner(dir, pre, suf, flags):
  225.     '''Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.'''
  226.     names = _get_candidate_names()
  227.     for seq in xrange(TMP_MAX):
  228.         name = names.next()
  229.         file = _os.path.join(dir, pre + name + suf)
  230.         
  231.         try:
  232.             fd = _os.open(file, flags, 384)
  233.             _set_cloexec(fd)
  234.             return (fd, file)
  235.         continue
  236.         except OSError:
  237.             e = None
  238.             if e.errno == _errno.EEXIST:
  239.                 continue
  240.             
  241.             raise 
  242.             continue
  243.         
  244.  
  245.     
  246.     raise IOError, (_errno.EEXIST, 'No usable temporary file name found')
  247.  
  248.  
  249. def gettempprefix():
  250.     '''Accessor for tempdir.template.'''
  251.     return template
  252.  
  253. tempdir = None
  254.  
  255. def gettempdir():
  256.     '''Accessor for tempdir.tempdir.'''
  257.     global tempdir
  258.     if tempdir is None:
  259.         _once_lock.acquire()
  260.         
  261.         try:
  262.             if tempdir is None:
  263.                 tempdir = _get_default_tempdir()
  264.         finally:
  265.             _once_lock.release()
  266.  
  267.     
  268.     return tempdir
  269.  
  270.  
  271. def mkstemp(suffix = '', prefix = template, dir = None, text = False):
  272.     """mkstemp([suffix, [prefix, [dir, [text]]]])
  273.     User-callable function to create and return a unique temporary
  274.     file.  The return value is a pair (fd, name) where fd is the
  275.     file descriptor returned by os.open, and name is the filename.
  276.  
  277.     If 'suffix' is specified, the file name will end with that suffix,
  278.     otherwise there will be no suffix.
  279.  
  280.     If 'prefix' is specified, the file name will begin with that prefix,
  281.     otherwise a default prefix is used.
  282.  
  283.     If 'dir' is specified, the file will be created in that directory,
  284.     otherwise a default directory is used.
  285.  
  286.     If 'text' is specified and true, the file is opened in text
  287.     mode.  Else (the default) the file is opened in binary mode.  On
  288.     some operating systems, this makes no difference.
  289.  
  290.     The file is readable and writable only by the creating user ID.
  291.     If the operating system uses permission bits to indicate whether a
  292.     file is executable, the file is executable by no one. The file
  293.     descriptor is not inherited by children of this process.
  294.  
  295.     Caller is responsible for deleting the file when done with it.
  296.     """
  297.     if dir is None:
  298.         dir = gettempdir()
  299.     
  300.     if text:
  301.         flags = _text_openflags
  302.     else:
  303.         flags = _bin_openflags
  304.     return _mkstemp_inner(dir, prefix, suffix, flags)
  305.  
  306.  
  307. def mkdtemp(suffix = '', prefix = template, dir = None):
  308.     """mkdtemp([suffix, [prefix, [dir]]])
  309.     User-callable function to create and return a unique temporary
  310.     directory.  The return value is the pathname of the directory.
  311.  
  312.     Arguments are as for mkstemp, except that the 'text' argument is
  313.     not accepted.
  314.  
  315.     The directory is readable, writable, and searchable only by the
  316.     creating user.
  317.  
  318.     Caller is responsible for deleting the directory when done with it.
  319.     """
  320.     if dir is None:
  321.         dir = gettempdir()
  322.     
  323.     names = _get_candidate_names()
  324.     for seq in xrange(TMP_MAX):
  325.         name = names.next()
  326.         file = _os.path.join(dir, prefix + name + suffix)
  327.         
  328.         try:
  329.             _os.mkdir(file, 448)
  330.             return file
  331.         continue
  332.         except OSError:
  333.             e = None
  334.             if e.errno == _errno.EEXIST:
  335.                 continue
  336.             
  337.             raise 
  338.             continue
  339.         
  340.  
  341.     
  342.     raise IOError, (_errno.EEXIST, 'No usable temporary directory name found')
  343.  
  344.  
  345. def mktemp(suffix = '', prefix = template, dir = None):
  346.     """mktemp([suffix, [prefix, [dir]]])
  347.     User-callable function to return a unique temporary file name.  The
  348.     file is not created.
  349.  
  350.     Arguments are as for mkstemp, except that the 'text' argument is
  351.     not accepted.
  352.  
  353.     This function is unsafe and should not be used.  The file name
  354.     refers to a file that did not exist at some point, but by the time
  355.     you get around to creating it, someone else may have beaten you to
  356.     the punch.
  357.     """
  358.     if dir is None:
  359.         dir = gettempdir()
  360.     
  361.     names = _get_candidate_names()
  362.     for seq in xrange(TMP_MAX):
  363.         name = names.next()
  364.         file = _os.path.join(dir, prefix + name + suffix)
  365.         if not _os.path.exists(file):
  366.             return file
  367.             continue
  368.     
  369.     raise IOError, (_errno.EEXIST, 'No usable temporary filename found')
  370.  
  371.  
  372. class _TemporaryFileWrapper:
  373.     '''Temporary file wrapper
  374.  
  375.     This class provides a wrapper around files opened for
  376.     temporary use.  In particular, it seeks to automatically
  377.     remove the file when it is no longer needed.
  378.     '''
  379.     
  380.     def __init__(self, file, name):
  381.         self.file = file
  382.         self.name = name
  383.         self.close_called = False
  384.  
  385.     
  386.     def __getattr__(self, name):
  387.         file = self.__dict__['file']
  388.         a = getattr(file, name)
  389.         if type(a) != type(0):
  390.             setattr(self, name, a)
  391.         
  392.         return a
  393.  
  394.     if _os.name != 'nt':
  395.         unlink = _os.unlink
  396.         
  397.         def close(self):
  398.             if not (self.close_called):
  399.                 self.close_called = True
  400.                 self.file.close()
  401.                 self.unlink(self.name)
  402.             
  403.  
  404.         
  405.         def __del__(self):
  406.             self.close()
  407.  
  408.     
  409.  
  410.  
  411. def NamedTemporaryFile(mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None):
  412.     '''Create and return a temporary file.
  413.     Arguments:
  414.     \'prefix\', \'suffix\', \'dir\' -- as for mkstemp.
  415.     \'mode\' -- the mode argument to os.fdopen (default "w+b").
  416.     \'bufsize\' -- the buffer size argument to os.fdopen (default -1).
  417.     The file is created as mkstemp() would do it.
  418.  
  419.     Returns a file object; the name of the file is accessible as
  420.     file.name.  The file will be automatically deleted when it is
  421.     closed.
  422.     '''
  423.     if dir is None:
  424.         dir = gettempdir()
  425.     
  426.     if 'b' in mode:
  427.         flags = _bin_openflags
  428.     else:
  429.         flags = _text_openflags
  430.     if _os.name == 'nt':
  431.         flags |= _os.O_TEMPORARY
  432.     
  433.     (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  434.     file = _os.fdopen(fd, mode, bufsize)
  435.     return _TemporaryFileWrapper(file, name)
  436.  
  437. if _os.name != 'posix' or _os.sys.platform == 'cygwin':
  438.     TemporaryFile = NamedTemporaryFile
  439. else:
  440.     
  441.     def TemporaryFile(mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None):
  442.         '''Create and return a temporary file.
  443.         Arguments:
  444.         \'prefix\', \'suffix\', \'directory\' -- as for mkstemp.
  445.         \'mode\' -- the mode argument to os.fdopen (default "w+b").
  446.         \'bufsize\' -- the buffer size argument to os.fdopen (default -1).
  447.         The file is created as mkstemp() would do it.
  448.  
  449.         Returns a file object.  The file has no name, and will cease to
  450.         exist when it is closed.
  451.         '''
  452.         if dir is None:
  453.             dir = gettempdir()
  454.         
  455.         if 'b' in mode:
  456.             flags = _bin_openflags
  457.         else:
  458.             flags = _text_openflags
  459.         (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  460.         
  461.         try:
  462.             _os.unlink(name)
  463.             return _os.fdopen(fd, mode, bufsize)
  464.         except:
  465.             _os.close(fd)
  466.             raise 
  467.  
  468.  
  469.